package com.example.admin.controller;

import com.example.admin.exception.AdminException;
import com.example.admin.model.User;
import com.example.admin.service.UserService;
import com.example.admin.utils.ReturnMessage;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/v1")
public class UserController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @GetMapping("/user/index")
    public ReturnMessage list(@RequestParam(required = false) String firstName,
                              @RequestParam(required = false) String phone,
                              @RequestParam(required = false, defaultValue = "0") int age,
                              @RequestParam(defaultValue = "0") int page,
                              @RequestParam(defaultValue = "10") int size) {
        Page<User> userList = userService.getList(firstName, phone, age, page, size);
        HashMap<String, Object> data = new HashMap<>();
        data.put("total", userList.getTotalElements());
        data.put("list", userList.getContent());
        return ReturnMessage.success(data);
    }

    @PostMapping("/user/store")
    public ReturnMessage store(@RequestBody @Validated User user) {
        userService.saveUser(user);
        return ReturnMessage.success("操作成功");
    }

    @PostMapping("/user/update/{id}")
    public ReturnMessage update(@PathVariable Long id, @RequestBody User user) {
        if (id == null) {
            throw new AdminException("参数不正确");
        }
        userService.updateUser(id, user);
        return ReturnMessage.success("操作成功");
    }

    @PostMapping("/user/delete/{id}")
    public ReturnMessage delete(@PathVariable Long id) throws Exception {
        if (id == null) {
            throw new AdminException("参数不正确");
        }
        userService.deleteUser(id);
        return ReturnMessage.success("操作成功");
    }
}
